package com.tocean.app.aspect;

import com.tocean.app.entity.sys.AccountOperationLog;
import com.tocean.app.mapper.sys.AccountOperationLogMapper;
import com.tocean.app.util.id.SnowflakeId;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.LocalVariableTableParameterNameDiscoverer;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.util.Date;

/**
 * 功能描述：
 *
 * @Author 梁展鹏
 * @Date 2020/8/6 10:02
 */
@Aspect
@Component
public class AccountOperationLogAnnotationAspect {

    @Autowired
    private AccountOperationLogMapper mapper;

    @Pointcut("@annotation(com.tocean.app.aspect.AccountOperationLogAnnotation)")
    public void pointcut() {
    }

    @Around("pointcut()")
    public Object around(ProceedingJoinPoint point) {
        Object result = null;

        long beginTime = System.currentTimeMillis();
        try {
            result = point.proceed(); // 执行方法
        } catch (Throwable e) {
            e.printStackTrace();
        }

        /* 保存日志 */
        saveLog(point, System.currentTimeMillis() - beginTime);

        return result;
    }

    private void saveLog(ProceedingJoinPoint joinPoint, Long responseTime) {
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();
        AccountOperationLogAnnotation _annotation = method.getAnnotation(AccountOperationLogAnnotation.class);

        AccountOperationLog _log = new AccountOperationLog();
        _log.setAccountId("");
        _log.setNickname("");
        _log.setOperation(null != _annotation ? _annotation.name() : ""); // 注解上的描述
        _log.setMethod(String.format("%s.%s()", joinPoint.getTarget().getClass().getName(), signature.getName())); // 请求的方法名
        _log.setResponseTime(responseTime);

        // 获取request
//        HttpServletRequest request = HttpContextUtils.getHttpServletRequest();
        _log.setIp("");

        // 请求的方法参数值
        Object[] args = joinPoint.getArgs();

        // 请求的方法参数名称
        LocalVariableTableParameterNameDiscoverer u = new LocalVariableTableParameterNameDiscoverer();
        String[] paramNames = u.getParameterNames(method);
        if (args != null && paramNames != null) {
            String params = "";
            for (int i = 0; i < args.length; i++) {
                params += "  " + paramNames[i] + ": " + args[i];
            }
            _log.setParams(params);
        }

        // 保存系统日志 todo
//        mapper.insert(_log);
    }

}
